package com.dx.mes.web;

import com.csvreader.CsvWriter;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.service.pojo.CSVPo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ChartDataController {
    @Value("${spcExcel.url}")
    private String spcExcelURL;
    ///导出CSV文件
    @RequestMapping(value = "/exportChartData.do")
    public String downloadFile(@ModelAttribute("csvPo") CSVPo csvPo, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        File csvFile = createCSVFile(csvPo);
        // File file = new File("E:/" + csvFile);
          if (csvFile.exists()) {
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" + csvFile.getName());
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(csvFile);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }

        return null;
    }

    //上传文件
    @RequestMapping(value = "/upload.do")
    @ResponseBody
    public List<String> upload(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
                               Model model, HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException {
        String filename = file.getOriginalFilename();
        InputStream fileInputStream = file.getInputStream();
        //4,存入数组
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            boolean is03Excel = filename.matches("^.+\\.(?i)(xls)$");
            //1、读取工作簿
            Workbook workbook = is03Excel ? new HSSFWorkbook(fileInputStream) : new XSSFWorkbook(fileInputStream);
            //2、读取工作表
            Sheet sheet = workbook.getSheetAt(0);

            //3、读取行
            if (sheet.getPhysicalNumberOfRows() > 2) {
                for (int k = 1; k < sheet.getPhysicalNumberOfRows(); k++) {
                    //4、读取单元格
                    Row row = sheet.getRow(k);
                    Cell cell0 = row.getCell(0);
                    arrayList.add(String.valueOf(cell0.getNumericCellValue()));
                }
            }
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrayList;
    }

    //生成CSV文件
    public File createCSVFile(CSVPo csvpo) {
        String filePath = spcExcelURL;
        File file = new File(filePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
        Timestamp timestamp = Util.getCurrentTimestamp();
        String nowTime = sFormat.format(timestamp);
        String[] arrTime = nowTime.split("-");
        nowTime = String.join("", arrTime);
        String csvFilePath = filePath + "/" + nowTime +"-"+ csvpo.getChart_no() + ".csv";
        File csvFile = new File(csvFilePath);

        String rawData = csvpo.getRawData();
        String chartData = csvpo.getChartData();
        String summaryData = csvpo.getSummaryData();
        List<String[]> rawList = null;
        if (!"[]".equals(rawData)){
             rawList = parseTheString(rawData);
        }
        List<String[]> chartList = parseTheString(chartData);
        List<String[]> summaryList = parseTheString(summaryData);

        try {
            CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("GBK"));
            // 写表头
            String[] header1 = {"原始数据"};
            String[] empty = {""};
            String[] header2 = {"管制图数据"};
            String[] header3 = {"汇总数据"};
            csvWriter.writeRecord(header1);
            if(rawList!=null){
                for (int i = 0; i < rawList.size(); i++) {
                    csvWriter.writeRecord(rawList.get(i));
                }
            }
            csvWriter.writeRecord(empty);
            csvWriter.writeRecord(header2);
            for (int i = 0; i < chartList.size(); i++) {
                csvWriter.writeRecord(chartList.get(i));
            }
            csvWriter.writeRecord(empty);
            csvWriter.writeRecord(header3);
            for (int i = 0; i < summaryList.size(); i++) {
                csvWriter.writeRecord(summaryList.get(i));
            }
            csvWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return csvFile;
    }

    public List<String[]> parseTheString(String data) {
        String rawDataD = data.substring(1, data.length() - 1);
        String[] rawDataDD = rawDataD.split("]");
        int rawDataRow = rawDataDD.length;// rawDataRow 行数
        String raw = "";
        List<String[]> rawList = new ArrayList<String[]>();
        for (int i = 0; i < rawDataRow; i++) {
            if (i == 0) {
                raw = rawDataDD[i].substring(1);
            } else {
                raw = rawDataDD[i].substring(2);
            }
            String[] rawArr = raw.split(",");
            List<String> newRawArr = new ArrayList<String>();
            for (int j = 0; j < rawArr.length; j++) {
                String rawdata = rawArr[j].substring(1, rawArr[j].length() - 1);
                newRawArr.add(rawdata);
            }
            String[] rawContent = newRawArr.toArray(new String[newRawArr.size()]);
            rawList.add(rawContent);
        }
        return rawList;
    }
}
